package top.zpengblog.kafkaprogram.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.Properties;

/**
 * @author linzp
 * @version 1.0.0
 * CreateDate 2020/11/19 21:08
 */
@Service
@Slf4j
public class KafKaConsumer {

    /**
     * 消费者.
     */
    private KafkaConsumer<String, String> consumer;

    /**
     * 结点.
     */
    @Value("${kafka.servers}")
    private String servers;

    /**
     * topic.
     */
    @Value("${kafka.topic}")
    private String topic;

    /**
     * 初始化.
     */
    @PostConstruct
    private void init() {
        Properties props = new Properties();
        props.put("bootstrap.servers", servers);
        // 每个消费者分配独立的组号
        props.put("group.id", "consumer-1");
        // 如果value合法，则自动提交偏移量
        props.put("enable.auto.commit", "true");
        // 设置多久一次更新被消费消息的偏移量
        props.put("auto.commit.interval.ms", "1000");
        // 设置会话响应的时间，超过这个时间kafka可以选择放弃消费或者消费下一条消息
        props.put("session.timeout.ms", "30000");
        // 自动重置offset
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        // 设置分区类,根据key进行数据分区
        consumer = new KafkaConsumer<String, String>(props);
        log.info("kafka 消费者启动成功！！！！！！！");
    }

    /**
     * 发送消息.
     *
     */
    public void consume() {
        consumer.subscribe(Collections.singletonList(topic));
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                log.info("offset = {}, key = {}, value = {}", record.offset(), record.key(), record.value());
            }
    }
}
